/*
 * uart.c
 *
 *  Created on: Nov 15, 2021
 *      Author: Abyss
 */
#include "main.h"
#include "sys.h"

extern UART_HandleTypeDef huart6;
extern UART_HandleTypeDef huart1;

#define RXdata_number 7 //传输数据
uint8_t RxBuffer;
uint8_t RxData[8];

extern int accelerator;

//printf重定向
#ifdef __GNUC__
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif

PUTCHAR_PROTOTYPE
{
	HAL_UART_Transmit(&huart6,(uint8_t *)&ch,1,100);//阻塞方式打印
  return ch;
}



//控制数据发送  数据线稿后低传输
//字头  数据 crc
void SendTo_plane(int fly_mode,int ch1,int ch2,int ch3,int ch4)
{
	char Rcrc[RXdata_number];
	uint8_t crc;
    //crc校验

	Rcrc[0] = 'M';
	Rcrc[1] = fly_mode;
	Rcrc[2] = ch1;
	Rcrc[3] = ch2;
	Rcrc[4] = ch3;
	Rcrc[5] = ch4;

	crc = crc8_maxim(Rcrc,RXdata_number-1);

	Rcrc[RXdata_number-1] = crc;

    HAL_UART_Transmit(&huart6, Rcrc, RXdata_number,  100);

}

//串口接收中断
int ctr_x1,ctr_y1,ctr_x2,ctr_y2,ctr_accelerator;

int up_date(char chh,char chl)  //将传输数据还原
{
  	int data;
  	data = chh;
  	data = (data<<8)&chl;
  	return data;
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
   static int flag = 0;
   static int count = 0;


	if(huart==&huart6)//判断，如果是串口6
    {

         if(flag==0)
         {
        	 if(RxBuffer=='M')  //判断字头一致接收
        	 {
        		 flag = 1;
        		 RxData[count] = RxBuffer;
        	 }
         }
         else  //持续接收  数据转化
         {
        	 RxData[++count] = RxBuffer;
        	 if(count==RXdata_number)
			 {
        		 count = 0;
        		 flag = 0;
				 uint8_t crc;
				 crc = crc8_maxim(RxData,RXdata_number-1);
				 if(crc == RxData[RXdata_number-1])  //校验crc是否相等
				 {
                    Fly_Mode = RxData[1];
                    ctr_x1 = RxData[2];
                    ctr_y1 = RxData[3];
                    ctr_x2 = RxData[4];
                    ctr_y2 = RxData[5];
				 }

			 }
         }
		 HAL_UART_Receive_IT(&huart6,&RxBuffer, 1);//该函数会开启接收中断：标志位UART_IT_RXNE，并且设置接收缓冲以及接收缓冲接收最大数据量
    }
}




